<template>
  <view class="feed">
      <view class="warehouse-drop-list">
        <u-row style="width: 100%">
          <u-col :span="6">
            <div class="home-drop-item " @click="openCategory(1)">
              <span class="drop-name">{{ dropItem.label || '选择日期' }}</span>
              <u-icon name="arrow-down-fill" color="#2498F6" size="24"></u-icon>
            </div>
          </u-col>
        </u-row>
     </view>
    <Box title="饲料消耗统计" show-title height="550rpx">
      <view class="charts-box">
        <view style="flex-grow: 1">
          <qiun-data-charts
              style="width: 100%;height: 420rpx"
              type="column"
              :opts="commonOption"
              :chartData="chartsDataColumn1"
          />
        </view>
        <view class="feed-chart1-static">
          <view class="feed-chart1-static-item">
            <view class="feed-chart1-static-item-value" style="color: #FF4E0C">{{ total }}吨</view>
            <view class="feed-chart1-static-item-label">总消耗</view>
          </view>
          <view class="feed-chart1-static-item">
            <view class="feed-chart1-static-item-value">{{ maxName || '暂无' }}</view>
            <view class="feed-chart1-static-item-label">消耗最多</view>
          </view>
          <view class="feed-chart1-static-item">
            <view class="feed-chart1-static-item-value">{{ minName || '暂无' }}</view>
            <view class="feed-chart1-static-item-label">消耗最少</view>
          </view>
        </view>
      </view>
    </Box>
    <Box title="饲料价格变化" show-title style="height: 470rpx">
      <div class="home-drop-item chart-drop" @click="openCategory(2)">
        <span class="drop-name">{{ matItem.label ||  '饲料种类'  }}</span>
        <u-icon name="arrow-down-fill" color="#2498F6" size="24"></u-icon>
      </div>
      <view class="charts-box">
        <qiun-data-charts
            style="width: 100%;height: 100%"
            type="area"
            :opts="areaOption"
            :chartData="chartsDataColumn2"
        />
      </view>
    </Box>
    <Box title="不同阶段饲料消耗及成本" show-title style="height: 470rpx">
      <div class="home-drop-item chart-drop" @click="openCategory(3)">
        <span class="drop-name">{{ stageItem.label ||  '全部阶段'  }}</span>
        <u-icon name="arrow-down-fill" color="#2498F6" size="24"></u-icon>
      </div>
      <view class="charts-box">

      </view>
    </Box>
<!--    饲料种类 -->
    <u-select
        :default-value="[defaultMat]"
        v-model="showMat"
        :list="matList"
        @cancel="showMat = false"
        @confirm="confirmMat">
    </u-select>
    <!--    阶段 -->
    <u-select
        :default-value="[defaultStage]"
        v-model="showStage"
        :list="stageList"
        @cancel="showStage = false"
        @confirm="confirmStage">
    </u-select>
    <u-picker
        v-model="showDate"
        mode="time"
        :start-year="2020"
        :end-year="ownYear"
        :params="{
          year: true,
					month: true,
					day: false,
					hour: false,
					minute: false,
					second: false
        }"
        @cancel="showDate = false"
        @confirm="confirmDate">
    </u-picker>

  </view>
</template>
<script>
import Box from "../../components/box.vue";
import dayjs from "dayjs";
import { mapState } from 'vuex'
export default {
  name: "feed",
  components: {Box},
  data() {
    return {
      ownYear: new Date().getFullYear(),
      showDate: false,
      dropItem: {
        value: dayjs().format('YYYY-MM'),
        label: dayjs().format('YYYY年MM月')
      },
      // 通用option
      commonOption: {
        legend: { show: false },
        padding: [60, 15, 10, 15],
        dataLabel: true,
        xAxis: {
          axisLineColor: '#B1B1B1',
          calibration: false,
          fontColor: '#B1B1B1',
          fontSize: 12,
          lineHeight: 20
        },
        yAxis: {
          disableGrid: true,
          data: [
            {
              calibration: false,
              fontColor: '#B1B1B1',
              fontSize: 12,
              lineHeight: 17
            }
          ]
        },
        extra: {
          column: {
            width: 16,
          }
        }
      },
      // 存栏
      chartsDataColumn1: {},
      total: 100,
      maxName: '种类',
      minName: '种类',
      chartsDataColumn2: {},
      chartsDataColumn3: {},
      /**
       * 饲料种类
       */
      matItem: {
      },
      showMat: false,
      matList: [],
      /**
       * 阶段
       */
      stageItem: {},
      showStage: false,
      stageList: [],
    };
  },
  computed: {
    ...mapState(['farm']),
    areaOption() {
      return  {
        ...this.commonOption,
      }
    },
    defaultMat() {
      return this.matList.findIndex(item => item.value == this.matItem.value)
    },
    defaultStage() {
      return this.stageList.findIndex(item => item.value == this.stageItem.value)
    }
  },
  created() {
  },
  methods: {
    requestData() {
      // 饲料种类
      this.$api.getMatList({
        date: this.dropItem.value,
      }).then(res => {
        this.matList = res.map(item => {
          return {
            label: item.matname,
            value: item.id
          }
        })
        if (res.length) {
          this.matItem = this.matList[0]
          this.requestMatPrice()
        }
        // 统计每个分类的出库数量之和
        let total = 0
        let chartList = []
        res.forEach(matItem => {
          let matValue = 0
          matItem.matouts.forEach(outItem => {
            total += outItem.outnum
            matValue += outItem.outnum
          })
          chartList.push({
            name: matItem.matname,
            value: matValue
          })
        })
        let xData = chartList.map(item => item.name)
        let yData = chartList.map(item => item.value)
        this.total = total
        // 计算最大值和最小值
        let max = Math.max.apply(null, yData)
        let min = Math.min.apply(null, yData)
        let maxIndex = yData.indexOf(max)
        let minIndex = yData.indexOf(min)
        this.maxName = xData[maxIndex]
        this.minName = xData[minIndex]
        // 按分类统计出库数量
        this.chartsDataColumn1 = {
          categories: xData,
          series: [{
            name: "饲料消耗统计",
            data: yData,
            color: '#2498F6',
            textColor: '#2498F6',
            textSize: 10,
          }]
        }
      })
    },
    // 根据分类统计饲料的入库平均价格
    requestMatPrice() {
      this.$api.getMatinAvgPrice({
        mat: this.matItem.value
      }).then(res => {
        // 按月统计
        let monthMap = {}
        res.forEach(item => {
          let month = dayjs(item.buytime).format('YYYY-MM')
          if (!monthMap[month]) {
            monthMap[month] = []
          }
          monthMap[month].push(item.price)
        })
        let xData = Object.keys(monthMap)
        let yData = []
        for (const monthMapKey in monthMap) {
          let avgPrice = monthMap[monthMapKey].reduce((pre, cur) => pre + cur, 0) / monthMap[monthMapKey].length
          yData.push(parseInt(avgPrice))
        }
        this.chartsDataColumn2 = {
          categories: xData,
          series: [{
            name: "饲料平均价格",
            data: yData,
            color: '#2498F6',
            textColor: '#2498F6',
            textSize: 10,
          }]
        }
      })
    },
    openCategory(index) {
      if (index === 1) {
        this.showDate = true
      }
      if (index === 2) {
        this.showMat = true
      }
      if (index === 3) {
        this.showStage = true
      }
    },
    confirmDate(value) {
      this.showDate = false
      this.dropItem = {
        value: `${value.year}-${value.month}`,
        label: `${value.year}年${value.month}月`
      }
      this.requestData()
    },
    // 确认选择饲料种类
    confirmMat(value) {
      this.showMat = false
      console.log(value)
      this.matItem = {
        ...value[0]
      }
      this.requestMatPrice()
    },
    // 确认选择阶段
    confirmStage(value) {
      this.showStage = false
      console.log(value)
    }
  },
  watch: {
    farm: {
      handler() {
        this.requestData()
      },
      deep: true,
      immediate: true
    },
  }
}
</script>
<style lang="scss">
.feed {
  height: 100%;
  padding: 0 30rpx 30rpx 30rpx;
  .warehouse-drop-list {
    padding: 20rpx 0;
  }
  .feed-chart1-static {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    .feed-chart1-static-item {
      flex: 1;
      text-align: center;
      .feed-chart1-static-item-value {
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: bold;
        font-size: 35rpx;
        color: #000000;
        line-height: 40rpx;
        text-align: center;
      }
      .feed-chart1-static-item-label {
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 500;
        font-size: 25rpx;
        color: #B1B1B1;
        line-height: 25rpx;
        text-align: center;
        margin-top: 20rpx;
      }
    }
  }
}
</style>
